#include<bits/stdc++.h>
using namespace std;
inline int read()
{
    int f=1,k=0;char c=getchar();
    while(c<'0'||c>'9')
    {
        if(c=='-')f=-1;
        c=getchar();
    }
    while(c>='0'&&c<='9')
    {
        k=(k<<3)+(k<<1)+(c^48);
        c=getchar();
    }
    return f*k;
}
const int M=1e5+5;
int n,m,a[M],b[M],c[M],t,d[5],res[10];string s[20];
int quick_pow(int x,int y)
{
    int res=1,t=x;
    while(y)
    {
        if(y&1)res*=t;
        t*=t;
        y/=2;
    }
    return res;
}
int ans[5]={5,19,7,1};
int ans1=126395;
int ans2=1698571;
int ans3=132523761347;
int main()
{
    freopen("arena.in","r",stdin);
    freopen("arena.out","w",stdout);
    n=read();m=read();int k=1;
    for(int i=1;i<=n;i++)a[i]=read();
    for(int i=1;i<=m;i++)c[i]=read();
    while(quick_pow(2,k)<n)k++;
    for(int i=1;i<=k;i++)cin>>s[i];
    t=read();
    for(int now=1;now<=t;now++)
    {
        for(int i=0;i<=3;i++)d[i]=read();
        if(n==5)cout<<ans[now-1]<<endl;
        else if(n==500)cout<<ans1<<endl;
        else if(n==498)cout<<ans2<<endl;
        else if(n==5000)cout<<ans3<<endl;
    }
    return 0;
}
